﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI.WebControls;
using System.Web.UI;

namespace Evpo.ContactData.CustomControls
{
    public class LookupDropDown : DropDownList, ILookupControl
    {
        #region Properties
        public string LookupName
        {
            get;
            set;
        }

        public bool Multiselect
        {
            get { return false; }
        }

        #endregion Properties

        #region Fields
        private LookupTools _lookupTools;
        #endregion Fields

        #region Handlers
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            if (String.IsNullOrEmpty(LookupName))
                return;
            _lookupTools = new LookupTools(this);
            _lookupTools.GetSelectedItems += new SelectedItemsEventHandler(LookupHost_GetSeletedItems);
            _lookupTools.SetSelectedItems += new SelectedItemsEventHandler(LookupHost_SetSelectedItems);
        }

        void LookupHost_SetSelectedItems(object sender, SelectedItemsEventArgs e)
        {
            if (!e.LookupName.Equals(this.LookupName, StringComparison.CurrentCultureIgnoreCase))
                return;

            e.IsLookupFound = true;
            if (e.SelectedItems.Count > 0)
                this.SelectedValue = Convert.ToString(e.SelectedItems[0]);
        }

        protected override void OnUnload(EventArgs e)
        {
            base.OnUnload(e);
            if (String.IsNullOrEmpty(LookupName) || _lookupTools == null)
                return;
            _lookupTools.GetSelectedItems -= new SelectedItemsEventHandler(LookupHost_GetSeletedItems);
            _lookupTools.SetSelectedItems -= new SelectedItemsEventHandler(LookupHost_SetSelectedItems);
        }

        void LookupHost_GetSeletedItems(object sender, SelectedItemsEventArgs e)
        {
            if (!e.LookupName.Equals(LookupName, StringComparison.CurrentCultureIgnoreCase))
                return;

            e.IsLookupFound = true;

            e.SelectedItems.Clear();

            int selectedValue;
            if(Int32.TryParse(this.SelectedValue, out selectedValue))
                e.SelectedItems.Add(selectedValue);
        }
        #endregion Handlers

        #region Methods
        #endregion Methods

    }
}
